//#include "stdafx.h"
#include "IOManager.h"
#include "Rendering/Engine.h"
#include <ctime>

IOManager* IOManager::mPtr = NULL;

//////////////////////////////////////////////////////////////////////////
int IOManager::Init()
{
	IsSpaceAlreadyPressed = false;
	// Initialize GLFW
	if( !glfwInit() )
	{
		Output::Print("glfwInit failed\n");
		system("PAUSE");
		return EXIT_FAILURE;
	}

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); // 4x antialiasing
	// 	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2); // We want OpenGL 3.3
	// 	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
	//glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

	// Open an OpenGL window
	if( !glfwOpenWindow( 600,600, 0,0,0,0,32,0, GLFW_WINDOW ))
	{
		return ErrorAndExit("glfwOpenWindow FAILED\n");
	}


	// Initialize GLEW
	//glewExperimental=true; // Needed in core profile
	if (glewInit() != GLEW_OK) 
	{
		return ErrorAndExit("Failed to initialize GLEW\n");
	}

	glfwSetWindowTitle( "Engin3d" );

	// Ensure we can capture the escape key being pressed below
	glfwEnable( GLFW_STICKY_KEYS | GLFW_MOUSE_CURSOR );
	
	mEngine->Init();

	mViewport->InitProjectionMat(45.f, 600, 600, 0.1f, 1000.f );


	mCamera = mEngine->GetScene()->GetMainCamera();

	return EXIT_SUCCESS;
}

//////////////////////////////////////////////////////////////////////////
void IOManager::RunEngine()
{
	clock_t tTime = clock();
	float tElapsedTime = 0.0f;
	// Main loop
	while( !ShouldExit() )
	{
		tElapsedTime = ((float)tTime - clock())/CLOCKS_PER_SEC;

		ProcessInputs();
		mEngine->SetViewPortMat(&mViewport->GetProjectionMatrix());
		mEngine->Update(tElapsedTime);
	}
}

//////////////////////////////////////////////////////////////////////////
void IOManager::ProcessInputs()
{
	if (mCamera == NULL)
	{
		return;
	}

	float tStep = 0.001f;

	if(IsSpaceAlreadyPressed && glfwGetKey( GLFW_KEY_SPACE ) == GLFW_RELEASE)
	{
		IsSpaceAlreadyPressed = false ;
		mEngine->ToggleTransposeMatrix();
	}
	else if(glfwGetKey( GLFW_KEY_SPACE ) == GLFW_PRESS && !IsSpaceAlreadyPressed)
	{
		IsSpaceAlreadyPressed = true;
	}

	if (glfwGetKey( GLFW_KEY_UP ) == GLFW_PRESS || glfwGetKey( 'w' ) == GLFW_PRESS)
	{
		mCamera->MoveForward(tStep, true);
	}
	else if (glfwGetKey( GLFW_KEY_DOWN ) == GLFW_PRESS|| glfwGetKey( 's' ) == GLFW_PRESS)
	{
		mCamera->MoveForward(-tStep, true);
	}
	
	if (glfwGetKey( GLFW_KEY_RIGHT ) == GLFW_PRESS|| glfwGetKey( 'd' ) == GLFW_PRESS)
	{
		mCamera->MoveRigth(tStep, true);
	}
	else if (glfwGetKey( GLFW_KEY_LEFT ) == GLFW_PRESS|| glfwGetKey( 'a' ) == GLFW_PRESS)
	{
		mCamera->MoveRigth(-tStep, true);
	}

	int tWidth, tHeight;
	glfwGetWindowSize(&tWidth, &tHeight);
	
}